package com.zuo_book.controller;

import com.zuo_book.common.Result;
import com.zuo_book.common.ResultCode;
import com.zuo_book.service.FileService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传控制器
 */
@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
public class FileController {

    private final FileService fileService;

    /**
     * 上传图片文件
     * @param file 文件
     * @return 文件访问URL
     * @throws IOException IO异常
     */
    @PostMapping("/upload/image")
    public Result<Map<String, String>> uploadImage(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return Result.failure(ResultCode.FAILED,"上传文件不能为空");
        }

        // 校验文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return Result.failure(ResultCode.FAILED,"只能上传图片文件");
        }

        // 上传文件并获取访问URL
        String fileUrl = fileService.uploadFile(file, "images");

        Map<String, String> data = new HashMap<>();
        data.put("url", fileUrl);

        return Result.success(data);
    }

    /**
     * 上传文档文件
     * @param file 文件
     * @return 文件访问URL
     * @throws IOException IO异常
     */
    @PostMapping("/upload/document")
    public Result<Map<String, String>> uploadDocument(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return Result.failure(ResultCode.FAILED,"上传文件不能为空");
        }

        // 校验文件类型
        String contentType = file.getContentType();
        if (contentType == null || !(
            contentType.equals("application/pdf") ||
            contentType.equals("application/msword") ||
            contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document") ||
            contentType.equals("text/plain"))) {
            return Result.failure(ResultCode.FAILED,"不支持的文件类型");
        }

        // 上传文件并获取访问URL
        String fileUrl = fileService.uploadFile(file, "documents");

        Map<String, String> data = new HashMap<>();
        data.put("url", fileUrl);

        return Result.success(data);
    }
}
